package com.nervenets.web.controller.handler.admin.user;

import com.alibaba.fastjson.JSON;
import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.hibernate.domain.user.UserRole;
import com.nervenets.web.redis.domain.user.UserStored;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

public class UserEditHandler extends SessionHandler<UserEditParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(UserEditParams params, HttpServletRequest request) throws Exception {
        User user = new User();
        if (params.getTargetUserId() > 0) {
            user = userDao.findById(params.getTargetUserId(), User.class);
            if (null == user) return errorMessage(MessageCode.code_444, "您编辑的用户不存在！");

            if (!params.getMobile().equals(user.getMobile())) {
                final User userByMobile = userDao.getUserByMobile(params.getMobile());
                if (null != userByMobile) return errorMessage(MessageCode.code_444, "该手机号码已经被其他用户占用");
                String code = user.getCode();
                User codeUser = userDao.getUserByCode(code);
                while (null != codeUser) {
                    code = StringUtils.randomUpperString(6);
                    codeUser = userDao.getUserByCode(code);
                }
                user.setCode(code);
            }
        }

        if (user.isNew()) {
            final User userByMobile = userDao.getUserByMobile(params.getMobile());
            if (null != userByMobile) return errorMessage(MessageCode.code_444, "该手机号码已经被注册");
        }

        final User inviteUser = userDao.getUserByCode(params.getCode());
        if (null == inviteUser) return errorMessage(MessageCode.code_444, "推荐码错误，不存在！");
        user.setInviteUserId(inviteUser.getId());
        user.setTeamUserId(inviteUser.getInviteUserId());

        user.setMobile(params.getMobile());
        user.setPassword(params.getPassword());
        user.setRole(JSON.parseObject(params.getRole(), UserRole.class));
        user.getInfo().setName(params.getName());
        user.setGender(params.getGender());
        user.setAreaId(params.getAreaId());
        userDao.saveOrUpdate(user);
        globalService.clearRedisUserStored(user.getId());
        return successMessage(user);
    }

    @Override
    public String result() throws Exception {
        return successMessage("用户信息");
    }
}
